/**
 * @author: welling
 */
Weifox.data = {
	users:null,
	deleteUser:function(user){
		for(var i=0;i<this.users.length;i++){
			if(this.users[i]==user){
				this.users.splice(i,1);
				this.saveUser();
				return;
			}
		}
	},
	
	/**
	 * 将新的User加到Preference
	 */
	addUser:function(user){
		if(this.checkUser(user)){
			alert('用户已存在,将覆盖旧的帐号');
			for (var i in ouser){
				if (i != "timeline") {//保留时间线的信息
					ouser[i]=user[i];
				}
			}
			
			this.saveUser();
			return;
		};
		//添加到
		this.users.push(user);
		this.setDefaultUser(user);
		//
		this.saveUser();
		Weifox.ui.addUser(user);
	},
	/**
	 * 不带参，只需在之前修改 this.users即可
	 */
	saveUser:function(){
		var w=Weifox;
		if(this.users==null)return;
		//解决一打开马上关闭FF时出现的清空用户Bug.因为是空了,所以存也没什么用.
		var text=JSON.stringify(this.users);
		
		var pref=w.browser.pref;
		pref.setCharPref('users',unescape(encodeURIComponent(text)));
	},
	/**
	 * 检查用户是否已存在。
	 * 返回用户对象 -存在
	 * null -不存在
	 */
	checkUser:function(user){
		var us=this.users;
		for(var i=0;i<us.length;i++){
			if(us[i].app==user.app&&us[i].user_id==user.user_id){
				return us[i];
			}
		}
		return null;
	},
	userTpl: {
		"app": "noapp",
		"method": "basic",
		"para1": "error",//用户名或oauth token
		"para2": "error",//密码或oauth secret
		"user_id": "noid",
		"user_name": "noname",
		"user_icon": "http://avatar2.fanfou.com/s0/00/8a/a1.jpg?1226210598",
		"timeline":{},
		//下面
		"collaspe": false,//树是否折叠
	},
	tlTpl:{
		label:'noname',
		disabled:false,//是否禁用
		autoUpdate:true,//自动更新
		icon:'',//图标
		lastUpdate:0,//上一次更新
		lastRead:0,
		unReadCount:0,
		interval:60000//更新时间
	},
	/*
	 * 验证User，使得和新版本的User结构相同
	 */
	validate:function(us){//us:array
//		var w=Weifox;
//		var version=w.browser.pref.getCharPref('version');
//		if(w.version==version){//如果版本一致不需验证
//			return;
//		}
//		w.browser.pref.setCharPref('version',w.version);
//		version=parseInt(version);
//		
//		if(version<0.08)//0.08以前的用户数据结果兼容
		for (var a = 0; a < us.length; a++) {
			var user=us[a];
			
			this.setDefaultUser(user);
		}
	},
	/*
	 * 按默认值设置User
	 */
	setDefaultUser:function(user){
		for(var i in this.userTpl){
			if(!user[i])user[i]=this.userTpl[i];
		}
		var w=Weifox;
		
		var appDefaultTimeline=w.apps[user.app].timeline;
		var timeline=user.timeline;
		for(var i in appDefaultTimeline){//如果有新增面板则添加
			if(!timeline[i])
				timeline[i]=w.util.clone(appDefaultTimeline[i]);
		}
		
		for (var t in timeline) {
			var x=timeline[t];
			//如果在各个App的时间线面板没有定义，则禁止这Timeline
			if(!appDefaultTimeline[t])x.disabled=true;
			
			for (var i in this.tlTpl)
				if (!x[i])x[i]=this.tlTpl[i];
		}
	},
	loadUser:function(){
		var w=Weifox;
		var pref=w.browser.pref;
		var text=decodeURIComponent(escape(pref.getCharPref('users')));
		var users=w.data.users=JSON.parse(text);
		
		this.validate(users);
		for(var i=0;i<users.length;i++){
			
			w.ui.addUser(users[i]);
		}
		/**var sql=D.SQLite;
		
		sql.queryData('weifox_user',D.TABLES.weifox_user.columns,'',function(result,columns){
			var c=null;
			var row;
//			try {
				while ((row = result.getNextRow())) {
					var user = {};
					for (var i = 0; i < columns.length; i++) {
						c = columns[i];
						user[c] = row.getResultByName(c);
					}
					users[user.id + ''] = user;
					Weifox.main.onUserDataLoaded(user);
				}
			//}catch(e){alert("sql:"+e)}
		});
		**/
	},
	/**
	 * 
	 * @param {Object} user_id
	 * @param {Object} app
	 * @param {Object} msg_id
	 * @param {Object} type 所属的Timeline
	 * @param {Object} time
	 * @param {Object} msg
	 */
	saveMsg:function(user_id,app,msg_id,type,time,msg){
			var sql = this.SQLite;
			var util = Weifox.util;
			/*
			sql.insertData('weibo',
			['user_id', 'app', 'msg_id', 'type', 'time', 'msg'], 
			[user_id, app, msg_id, type, time, (encodeURIComponent(JSON.stringify(msg)))]);*/
			
			//sql.insertData(app+user_id+type,['time','msg'],[time,encodeURIComponent(util.JSON.encode(msg))]);
	},
	
	/**
	 * 用一个用户和一个应用类型确定一条微博,反回一个数组
	 * @param {Object} user_id
	 * @param {Object} app
	 */
	getMsg:function(user_id,app,type){
		
	},
    SQLite: {
        Cc: Components.classes,
        Ci: Components.interfaces,
        _service: null,
        _connection: null,
        init: function(){
            var file = this.Cc["@mozilla.org/file/directory_service;1"].getService(this.Ci.nsIProperties).get("ProfD", this.Ci.nsIFile);
            file.append("weifox.sqlite");
            _service = this.Cc["@mozilla.org/storage/service;1"].getService(this.Ci.mozIStorageService);
            // Will also create the file if it does not exist
            _connection = _service.openDatabase(file);
			
			//创建 一个微博数据库
			/*
			this.createTable('weibo', 
			"user_id           TEXT NOT NULL," +
			"app         TEXT ," +
			"msg_id      TEXT NOT NULL," +
			"type		TEXT ," +
			"time		TEXT ," +
			"msg		TEXT," +
			"constraint pk_weibo primary key (app,msg_id)");*/
        },
        createTable: function(name, schema){
			if(!_connection.tableExists(name))
            	_connection.createTable(name, "time INTEGER PRIMARY KEY,msg NOT NULL");
        },
        /**
         * eg. Weifox.data.SQLite.insertData('weifox_user',['app','user_name'],["tencent","weifox"]);
         *
         * @param {Object} name
         * @param {Array} columns
         * @param {Array} data 
         */
        insertData: function(name, columns, data){
			this.createTable(name);
			
			for(var i=0;i<data.length;i++){
				data[i]='"'+data[i]+'"';
			}
            var sql = "INSERT OR REPLACE INTO " + name + "(" + columns.join(',') + ") values(" + data.join(',') + ")";
			//alert(sql);
			_connection.executeSimpleSQL(sql);
        },
        deleteData: function(){
        
        },
		/**
		 * 
		 * @param {Object} name
		 * @param {Object} columns
		 * @param {Object} query
		 * @param {Object} onget 回调函数,参数为二维数组,结果集会按参数的顺序返回.
		 */
        queryData: function(name, columns, query,onget){
            var sql = "SELECT " + columns.join(',') + " from " + name;
            if (query && query.length > 2) {
                sql += " where " + query;
            }
			var stm=_connection.createStatement(sql);
            stm.executeAsync({
                handleResult: function(aResultSet){
					/*
					var res=new Array();
					var row;
                    while ( (row = aResultSet.getNextRow())) {
						var r=new Array();
                        for(var i=0;i<columns.length;i++)
							r.push(row.getResultByName(columns[i]));
						
						res.push(r);
                    }*/
					onget(aResultSet,columns);
                },
                
                handleError: function(aError){
                    alert("Error: " + aError.message);
                },
                
                handleCompletion: function(aReason){
                    if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) 
                        alert("Query canceled or aborted!");
                }
            });
            
        },
		/**
		 * 
		 * @param {Object} table 一个包含columns types属性的对象
		 */
		generateSchema:function(table){
			var str='';
			var col=table.columns;
			var t=table.types;
			var i=0;
			for(;i<col.length-1;i++){
				str+=col[i]+' '+t[i]+' ,';
			}
			str+=col[i]+' '+t[i];
			return str;
		}
        
    },
    debug: function(){
        //var sql=Weifox.data.SQLite.createTable('weifox_user',Weifox.data.TABLES['weifox_user']);
        //Weifox.data.SQLite.insertData('weifox_user','app,user_name','"tencent","weifox"')
        var s = Weifox.data.SQLite.queryData('weifox_user', ['id','app','id'], 'id=1',function(c){
			//alert(c.toString())
		});
    }
};

//Weifox.data.User.loadUser();
